package com.nidu.demo.file.executor.command;

import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.file.ability.FileConfigDomainService;
import com.nidu.demo.file.gateway.FileGateway;
import com.nidu.demo.file.model.File;
import com.nidu.demo.file.model.FileConfig;
import com.nidu.demo.file.storage.FileStorage;
import com.nidu.demo.file.storage.FileStorageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * 文件删除命令执行器
 *
 * @author auto
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FileDeleteCmdExe {

    private final FileConfigDomainService configDomainService;
    private final FileGateway gateway;
    private final FileStorageFactory fileStorageFactory;

    /**
     * 删除文件
     *
     * @param id 文件ID
     */
    @Transactional
    public void execute(Long id) {
        // 1. 获取文件信息
        File file = gateway.getById(id);
        if(file == null){
            throw new BizException(ErrorCodeConstants.FILE_NOT_FOUND.getCode(), ErrorCodeConstants.FILE_NOT_FOUND.getMessage());
        }

        // 2. 获取文件配置
        FileConfig fileConfig = configDomainService.getConfig();
        
        // 3. 获取存储实现
        FileStorage fileStorage = fileStorageFactory.getFileStorage(fileConfig.getStorage());
        
        // 4. 从存储系统删除文件
        try {
            fileStorage.delete(file.getPath(), fileConfig.getConfig());
        } catch (Exception e) {
            log.warn("删除存储文件失败: {}", e.getMessage());
        }
        
        // 5. 删除数据库记录
        gateway.deleteById(id);
    }

    /**
     * 批量删除文件
     *
     * @param fileIds 文件ID集合
     */
    @Transactional
    public void execute(Set<Long> fileIds) {
        for (Long fileId : fileIds) {
            execute(fileId);
        }
    }
}
